package team.archai.nexus.boot.tool;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @program: tiny-dust-boot-build
 * @description: web 工具类
 * @author: lishibin
 * @create: 2021-02-24 19:51
 **/
public class WebUtil extends WebUtils {

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();

    }

    public static String getHeader(String headerKey) {
        HttpServletRequest request = getRequest();
        return request == null ? null : request.getHeader(headerKey);

    }

    public static final String USER_AGENT_HEADER = "user-agent";
    public static final String UN_KNOWN = "unknown";

    public WebUtil() {
    }

    public static boolean isBody(HandlerMethod handlerMethod) {
        ResponseBody responseBody = (ResponseBody) ClassUtil.getAnnotation(handlerMethod, ResponseBody.class);
        return responseBody != null;
    }

    @Nullable
    public static String getCookieVal(String name) {
        HttpServletRequest request = getRequest();
        Assert.notNull(request, "request from RequestContextHolder is null");
        return getCookieVal(request, name);
    }

    @Nullable
    public static String getCookieVal(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie != null ? cookie.getValue() : null;
    }

}
